package com.baomidou.config.util;

import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;

/**
 * mybatisplus-maven-plugin2
 *
 * @author MrYe
 * @Description
 * @date 2021-11-12 16:45
 */
public class HttpUtil {

    private static Log log = new SystemStreamLog();

    private HttpUtil() {
    }

    public static String readToken(String serverUrl, String params) {
        try {
            URL getUrl = new URL(serverUrl);
            final HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.getOutputStream().write(params.getBytes());
            connection.connect();
            Map<String, List<String>> headerMap = connection.getHeaderFields();
            connection.disconnect();
            if (null != headerMap) {
                List<String> cookies = headerMap.get("Set-Cookie");
                Optional<String> optional = cookies.stream().filter(c -> c.startsWith("xforce-saas-token")).findFirst();
                return optional.map(s -> {
                    String str = s.split("=")[1];
                    return str.substring(0, str.indexOf(";"));
                }).orElse(null);
            }
        } catch (Exception e) {
            log.error(e);
        }
        return null;
    }

    public static String changeToken(String serverUrl, String sourceToken, String params) {
        try {
            URL getUrl = new URL(serverUrl);
            final HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("cookie", "xforce-saas-token=" + sourceToken + ";");
            connection.setRequestMethod("POST");
            if (StringUtils.isNotBlank(params)) {
                connection.setDoOutput(true);
                connection.getOutputStream().write(params.getBytes());
            }
            connection.connect();
            Map<String, List<String>> headerMap = connection.getHeaderFields();
            connection.disconnect();
            if (null != headerMap) {
                List<String> cookies = headerMap.get("Set-Cookie");
                Optional<String> optional = cookies.stream().filter(c -> c.startsWith("xforce-saas-token")).findFirst();
                return optional.map(s -> {
                    String str = s.split("=")[1];
                    return str.substring(0, str.indexOf(";"));
                }).orElse(null);
            }
        } catch (Exception e) {
            log.error(e);
        }
        return null;
    }

    public static <T> T readSchema(String token, String serverUrl, Class<T> tClass) {
        try {
            URL getUrl = new URL(serverUrl);
            final HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("xforce-saas-token", token);
            connection.setRequestMethod("GET");
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            final StringBuilder sb = new StringBuilder();
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            return JSON.parseObject(sb.toString(), tClass);
        } catch (Exception e) {
            log.error(e);
            return null;
        }
    }

}
